<template>
	<div>
		<a-layout>
			<a-layout-content style="background: #fff">
				<a-page-header>
					<template slot="extra">
						<a-button @click="reload()" v-has="'incpuser.query'">
							<a-icon type="reload" />
						</a-button>
						<a-button
							type="primary"
							@click="addIncpUser"
							v-has="'incpuser.create'"
						>
							<a-icon type="file-add" />
							添加
						</a-button>
						<a-button type="primary" @click="exportTable">
							<a-icon type="export" />
							导出
						</a-button>
					</template>
					<template slot="title"> {{ $route.meta.title }} </template>
				</a-page-header>

				<a-card :bordered="false">
					<a-form-model layout="inline">
						<a-form-model-item>
							<a-input
								v-model="queryForm.searchkey"
								placeholder="cp名称/用户名"
							>
								<a-icon
									slot="prefix"
									type="copyright"
									style="color: rgba(0, 0, 0, 0.25)"
								/>
							</a-input>
						</a-form-model-item>
						<a-form-model-item>
							<a-select
								style="width: 120px"
								@change="handleOrderChange"
								allowClear
								placeholder="排序"
							>
								<a-select-option value="1">下单时间升序</a-select-option>
								<a-select-option value="2">下单时间降序</a-select-option>
								<a-select-option value="3">更新时间升序</a-select-option>
								<a-select-option value="4">更新时间降序</a-select-option>
							</a-select>
						</a-form-model-item>

						<a-form-model-item>
							<a-button
								v-has="'incpuser.query'"
								html-type="submit"
								@click="search"
								:disabled="!queryForm.searchkey && !queryForm.order_tag"
							>
								查询
							</a-button>
						</a-form-model-item>
						<a-form-model-item>
							<a-button
								v-has="'incpuser.query'"
								@click="clear"
								:disabled="!queryForm.searchkey && !queryForm.status"
							>
								<a-icon type="delete" />
								清空
							</a-button>
						</a-form-model-item>
					</a-form-model>
				</a-card>
				<div class="enlarge">
					<div class="mark" ref="mark" @click="closeMark">
						<img class="mark-img" :src="markImg" alt="" />
						<span class="iconfont icon-guanbi"> </span>
					</div>
				</div>

				<div style="margin: 10px 16px 0 16px">
					<a-table
						:scroll="{ x: calcTableWidth(columns) }"
						:columns="columns"
						:data-source="data"
						@change="handleTableChange"
						:loading="loading"
						:pagination="pagination"
						:rowKey="
							(record, index) => {
								return index
							}
						"
					>
						<!-- 自定义表头内容 -->

						<!-- 自定义单元格列的内容 -->
						<span
							slot="avatar"
							style="width: 15px; height: 15px"
							slot-scope="text, record"
						>
							<!-- <img
								@click="enlarge($event)"
								style="width: 40%; height: 40%"
								:src="'https://img10.360buyimg.com/n1/s450x450_jfs/t1/214844/13/1820/120684/617674afE8058a74a/b55a33d132d16158.jpg'"
								alt=""
							/> -->

							<img
								@click="enlarge($event)"
								v-if="record.avatar"
								style="width: 40%; height: 40%"
								:src="record.avatar"
								alt=""
							/>
						</span>

						<template v-slot:username="{ username }">
							<a-tooltip :title="username" placement="topLeft">
								{{ username }}
							</a-tooltip>
						</template>

						<template v-slot:updated_at_show="{ updated_at_show }">
							<a-tooltip :title="updated_at_show" placement="topLeft">
								{{ updated_at_show }}
							</a-tooltip>
						</template>

						<template v-slot:incp_name="{ incp_name }">
							<a-tooltip :title="incp_name" placement="topLeft">
								{{ incp_name }}
							</a-tooltip>
						</template>

						<template v-slot:market_name="{ market_name }">
							<a-tooltip :title="market_name" placement="topLeft">
								{{ market_name }}
							</a-tooltip>
						</template>

						<template v-slot:created_at="{ created_at }">
							<a-tooltip :title="formatDate(created_at)" placement="topLeft">
								{{ formatDate(created_at) }}
							</a-tooltip>
						</template>

						<span
							slot="status"
							slot-scope="text, record"
							style="white-space: nowrap"
						>
							<template>
								<a-badge
									:status="statusTypeFilter(record.status)"
									:text="statusFilter(record.status)"
								/>
							</template>
						</span>

						<template v-slot:updated_at="{ updated_at }">
							<a-tooltip :title="formatDate(updated_at)" placement="topLeft">
								{{ formatDate(updated_at) }}
							</a-tooltip>
						</template>
						<span slot="action" slot-scope="text, record">
							<template>
								<a @click="deleteIncp(record)" v-has="'incpuser.delete'"
									>删除</a
								>
								<a-divider type="vertical" />
								<a @click="updateIncp(record)" v-has="'incpuser.update'"
									>修改</a
								>
							</template>
						</span>
					</a-table>
				</div>
			</a-layout-content>
		</a-layout>
		<handle-table
			ref="handleTable"
			@handleOk="handleTableChange"
		></handle-table>
	</div>
</template>

<script>
	const tableObj = require("./json/table.json")
	import IncpUser from "@/api/incpuser"
	import momentUtil from "@/utils/day"
	import handleTable from "./components/handleForm.vue"
	export default {
		name: "incpuser",
		data() {
			this.statusMap = {
				1: {
					status: "success",
					text: "正常",
				},
				0: {
					status: "default",
					text: "停用",
				},
				"-1": {
					status: "error",
					text: "冻结",
				},
			}
			return {
				markImg: "",
				queryForm: {
					order_tag: "",
					searchkey: "",
					status: undefined, //placeholder 生效
				},
				data: [],
				columns: tableObj.columns,
				loading: false,
				pagination: {
					current: 1,
					pageSize: 20,
					total: 0,
					totalPage: 0,
					showSizeChanger: true,
					showTotal: (total) => `总 ${total} 条`,
				},
			}
		},

		filters: {
			formatStamp(stamp) {
				console.log(momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss"))
				return momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss")
			},
		},
		created() {
			this.getData()
		},
		methods: {
			reload() {
				window.location.reload()
			},
			calcTableWidth(columns) {
				let totalWidth = 0
				for (let i = 0, len = columns.length; i < len; i++) {
					if (columns[i].width) {
						totalWidth += columns[i].width
					} else {
						totalWidth += 120
					}
				}
				return totalWidth
			},
			closeMark({ target }) {
				console.log(target)
				if (target.nodeName === "DIV" || target.nodeName === "SPAN") {
					this.$refs["mark"].style.display = "none"
					this.markImg = ""
				}
			},
			enlarge({ target }) {
				this.$refs["mark"].style.display = "block"
				this.markImg = target.src
				console.log(target)
			},
			formatDate(timeStr) {
				if (["", "undefined", "null", "NaN", "false"].includes(timeStr + ""))
					return
				// console.log(
				// 	timeStr,
				// 	+new Date(timeStr),
				// 	this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
				// )
				return this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
			},
			deleteIncp(record) {
				console.log(record)
				this.$modal.confirm({
					title: "提示",
					content: "是否删除？",
					okText: "确定",
					cancelText: "取消",
					centered: true,
					onOk: () => {
						console.log("删除")
						IncpUser.delete(record.id).then((response) => {
							console.log(response)
							if (response.code !== 1) {
								this.$message.error(response.message)
								return
							}
							this.getData()
							this.$message.success(response.message)
							// this.queryForm()
						})
					},
					onCancel: () => {
						this.$message.warning("删除取消了")
					},
				})
			},
			updateIncp(item) {
				console.log(item)
				console.log(this.$refs.handleTable)
				this.$refs.handleTable.showModal("update", item)
			},

			handleTableChange(pagination, filters, sorter) {
				console.table(
					[
						{
							pagination: pagination,
							filters: filters,
							sorter: sorter,
						},
					],
					["pagination", "filters", "sorter"]
				)
				if (sorter) {
					if (sorter.order) {
						Object.assign(this.queryForm, {
							order_by: `${sorter.columnKey} ${sorter.order.slice(0, -3)}`,
						})
					} else {
						delete this.queryForm.order_by
					}
				}
				this.pagination = pagination || this.pagination
				this.getData()
			},
			handleOrderChange(value) {
				this.queryForm.order_tag = value
				this.getData()
			},
			getData() {
				this.loading = true
				let pageMap = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
				}
				IncpUser.query(Object.assign(pageMap, this.queryForm))
					.then((res) => {
						console.log(res)
						this.loading = false
						if (res.code == 1) {
							this.pagination.total = res.page.totalSize
							this.pagination.totalPage = res.page.totalPage
							//dataSource 默认将每列数据的 key 属性作为唯一的标识
							//处理数据，否则需要excel代码里处理了
							this.data = res.data.map((item, index) => {
								return Object.assign(item, { index: index + 1 })
							})
							// ========================
							// if (this.data.length === 0) {
							// 	this.data = [
							// 		{ id: "1", name: "a" },
							// 		{ id: "2", name: "b" },
							// 	]
							// }
							// ========================
							console.log(this.data)
						}
					})
					.catch((e) => {
						this.loading = false
					})
			},
			exportTable() {
				this.$excelUtil.genTable({
					excelName: `${this.$route.meta.title}`,
					columns: tableObj.columns,
					tableData: this.handleData(this.data),
					filterKeys: ["action"],
				})
			},
			//解析数据中不能识别部分
			handleData(data) {
				return data.map((item) => {
					return Object.assign({}, item, {
						avatar: item.avatar,
						updated_at: this.formatDate(item.updated_at),
						created_at: this.formatDate(item.created_at),
						status: this.statusFilter(item.status),
						// created_at: this.formatDate(item.created_at),
						// updated_at: this.formatDate(item.updated_at),
					})
				})
			},
			addIncpUser() {
				this.$refs.handleTable.showModal("add")
			},
			statusFilter(status) {
				if (!(status + "")) return
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].text
					: undefined
			},
			statusTypeFilter(status) {
				if (!(status + "")) return
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].status
					: undefined
			},
			search() {
				this.data = []
				this.pagination.page = 1
				this.getData()
			},
			clear() {
				this.queryForm.searchkey = ""
				this.queryForm.status = undefined
				this.getData()
			},
		},
		components: {
			handleTable,
			// detailPage,
		},
	}
</script>

<style lang="less" type="text/less" scoped>
	.enlarge {
		// box-sizing: border-box;
		// // padding: 15px;
		// margin-top: 35px;
		// overflow: auto;
		// height: calc(100% - 100px);
		.mark {
			display: none;
			width: 100vw;
			height: 100vh;
			// background: #000;
			// opacity: 0.5;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 99;
			position: fixed;
			left: 0;
			top: 0;
			.mark-img {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				width: 350px;
				height: 350px;
				z-index: 99;
			}
			.icon-guanbi {
				position: absolute;
				right: 50px;
				top: 50px;
				// color: #606266;
				color: #fff;

				font-size: 36px;
				cursor: pointer;
			}
		}
	}
</style>